import Taro , { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { observer } from '@tarojs/mobx'
import { ToastUtil, TYPES, DEFAULT_TYPE }  from '../../utils/toastUtil'

import './index.scss'

@observer
class Index extends Component {

  static options = {
    addGlobalClass: true
  }

  state={
    isShow: false,
    msg: '',
    type: DEFAULT_TYPE,
    className: ''
  }
  componentDidMount() {
    // Taro.eventCenter.on(ToastUtil.getEventName(), this.setToastAttr, this)
    ToastUtil.listen(this.setToastAttr, this)
  }

  componentWillUnmount() {
    ToastUtil.remove()
  }

  setToastAttr({ type, info, show }) {
    this.setState({ isShow: show, msg: info, type, className: ''}, () => {
      this.setClassName()
      this.clearToastAttr()
    })
  }

  setClassName() {
    const { isShow, type } = this.state
    let className = ''
    if(TYPES.indexOf(type) >= 0) {
      className += ` is-${type}`
    }
    if (isShow) {
      className += ' ani'
    }
    this.setState({ className })
  }

  clearToastAttr() {
    const { isShow } = this.state
    if (isShow) {
      this.TimerID && clearTimeout(this.TimerID)
      this.TimerID = setTimeout(() => {
        this.TimerID && clearTimeout(this.TimerID)
        ToastUtil.hide()
      }, 2000)
    }
  }

  render() {
    const { isShow, msg, className } = this.state
    return (
      <View>
        { isShow && <View className={'toast is-button' + className}>{msg}</View> }
      </View>
    );
  }
}
export default Index;